package com.zhku.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhku.yygh.hosp.respository.DepartmentRepository;
import com.zhku.yygh.hosp.service.DepartmentService;
import com.zhku.yygh.model.hosp.Department;
import com.zhku.yygh.vo.hosp.DepartmentQueryVo;
import com.zhku.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @BelongsProject: yygh-parent
 * @BelongsPackage: com.zhku.yygh.hosp.service.impl
 * @Author: "deweyMDH"
 * @CreateTime: 2023-05-14  19:36
 * @Version: 1.0
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        // paramMap 转换成department对象
        String paramJsonString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(paramJsonString, Department.class);

        // 根据医院编号 和 科室编号 查询
        Department departmentExist  = departmentRepository
                .getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        if (null != departmentExist){   // 修改
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(departmentExist);
        } else {    // 新增
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }

    }

    @Override
    public Page<Department> findPageDepartment(int page, int limit,  DepartmentQueryVo departmentQueryVo) {
        //0为第一页
        Pageable pageable = PageRequest.of(page-1, limit);
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例, 这个模板按照 matcher 模式， 查找department 这种对象
        Example<Department> example = Example.of(department, matcher);

        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(null != department) {
            //departmentRepository.delete(department);
            departmentRepository.deleteById(department.getId());
        }
    }

    //根据医院编号，查询医院所有科室列表
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //创建list集合，用于最终数据封装
        List<DepartmentVo> result = new LinkedList();

        //根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example example = Example.of(departmentQuery);

        //所有科室列表 departmentList
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室， 使用流的形式筛选 k大科室1 --> v[小科室1，2 ...]
        Map<String, List<Department>> departmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //遍历map集合 deparmentMap
        for(Map.Entry<String,List<Department>> entry : departmentMap.entrySet()) {
            //大科室编号
            String bigcode = entry.getKey();
            //大科室编号对应的全局数据
            List<Department> deparmentListChild = entry.getValue();

            //封装大科室 的 返回数据类型vo
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(bigcode);
            // 是因为，使用流筛选的时候，第一个 键值对entry 就是 大科室编号Bigcode - list<Department>
            // 此时，指针已经向后移动一个位置，下面就是子节点的数据
            departmentVo.setDepname(deparmentListChild.get(0).getBigname());

            //封装小科室
            List<DepartmentVo> children = new LinkedList();
            DepartmentVo departmentVoChild = new DepartmentVo();
            for (Department department : deparmentListChild){
                departmentVoChild = new DepartmentVo();
                departmentVoChild.setDepcode(department.getDepcode());
                departmentVoChild.setDepname(department.getDepname());
                //封装到list集合
                children.add(departmentVoChild);
            }
            //把小科室list集合放到大科室children里面
            departmentVo.setChildren(children);
            //放到最终result里面
            result.add(departmentVo);
        }

        return result;
    }

    //根据科室编号，和医院编号，查询科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(null != department) {
            return department.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(null != department) {
            return department;
        }
        return null;
    }
}
